<template>
    <div class="e-form">
        <BillTop title="调价结算详情" @cancel="handleClose"></BillTop>
        <div class="tabs warningTabs" v-if="Object.keys(formData).length != 0">
            <el-tabs
                tab-position="left"
                v-model="tabsName"
                @tab-click="onChangeTab"
            >
                <!-- 基本信息 -->
                <el-tab-pane
                    label="基本信息"
                    name="baseInfo"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="结算明细"
                    name="settlement"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="服务费用"
                    name="serviceCharge"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="附件信息"
                    name="accessory"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="审核历史"
                    name="auditHistory"
                    :disabled="clickTabFlag"
                ></el-tab-pane>

                <div>
                    <!-- 基本信息 -->
                    <div id="baseInfoCon" class="con">
                        <div class="e-form">
                            <div class="tabs">
                                <div class="tabs-title" id="baseInfo">
                                    基本信息
                                </div>
                                <div style="width: 100%" class="form">
                                    <el-form
                                        :model="formData"
                                        label-width="150px"
                                        :rules="formDataRules"
                                        ref="formDataRef"
                                    >
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item label="结算编号">
                                                    {{ formData.billNo }}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item label="单据机构">
                                                    {{ formData.orgName }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="结算类型"
                                                    prop="businessType"
                                                >
                                                    {{businessType}}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item label="源单编号">
                                                    <span>
                                                        {{
                                                            formData.sourceBillNo
                                                        }}
                                                        <i
                                                            slot="suffix"
                                                            class="
                                                                el-input__icon
                                                                el-icon-document-copy
                                                            "
                                                            @click="
                                                                sourceBillNoClick
                                                            "
                                                            v-if="
                                                                formData.sourceBillNo
                                                            "
                                                        ></i>
                                                    </span>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="结算单位"
                                                    prop="settlementUnitName"
                                                >
                                                    {{formData.settlementUnitName}}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="结算日期"
                                                    prop="settlementDate"
                                                >
                                                    {{formData.settlementDate}}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="结算金额(元)"
                                                    prop="amount"
                                                >
                                                    {{ formData.amount }}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item label="验收人员">
                                                    {{formData.acceptancePersonnelName}}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item label="发票编号">
                                                    {{formData.invoiceNo}}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="服务费用(含税,元)"
                                                >
                                                    {{ formData.freight }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="税率%"
                                                    prop="taxRate"
                                                >
                                                    {{formData.taxRate}}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="税价合计"
                                                    prop="totalAmount"
                                                >
                                                    {{ formData.totalAmount }}
                                                    元
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="税额"
                                                    prop="taxAmount"
                                                >
                                                    {{formData.taxAmount}}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item label="税额差额">
                                                    {{ formData.taxDifference }}
                                                    元
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="币种"
                                                    prop="currency"
                                                >
                                                    {{ formData.currency }}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="本位币"
                                                    prop="baseCurName"
                                                >
                                                    {{ formData.baseCurName }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="传财务共享"
                                                >
                                                    {{ formData.easId ? '已传' : '未传'}}
                                                </el-form-item>
                                            </el-col>

                                            <el-col :span="12">
                                                <el-form-item
                                                    label="本位币汇率"
                                                    prop="baseCurRate"
                                                >
                                                    {{formData.baseCurRate}}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-form-item label="备注">
                                               {{formData.remarks}}
                                            </el-form-item>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item label="状态">
                                                    {{
                                                        showState(
                                                            formData.state
                                                        )
                                                    }}
                                                    <!-- 草稿/审核中/已审核/已关闭/已作废 -->
                                                </el-form-item>
                                            </el-col>
                                            <el-col
                                                :span="12"
                                                v-if="
                                                    formData.redBillState !== -1
                                                "
                                            >
                                                <el-form-item label="冲红单">
                                                    <span
                                                        :style="
                                                            redBillStateStyle
                                                        "
                                                        >{{
                                                            redBillStateFun
                                                        }}</span
                                                    >
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row
                                            v-if="
                                                formData.state === 5
                                            "
                                        >
                                            <el-col :span="12">
                                                <el-form-item label="作废人：">
                                                    <span>{{
                                                        formData.nullifyCreator
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="作废原因："
                                                >
                                                    <span>{{
                                                        formData.nullifyReason
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row
                                            v-if="
                                                formData.state === 5
                                            "
                                        >
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="作废说明："
                                                >
                                                    <span>{{
                                                        formData.nullifyDescription
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="作废时间："
                                                >
                                                    <span>{{
                                                        formData.nullifyCreated
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                    </el-form>
                                </div>
                            </div>
                        </div>

                        <!-- ------------------------------------------------------------------------------------- -->
                    </div>

                    <!-- 结算明细 -->
                    <div id="settlementCon" class="con">
                        <div class="tabs-title" id="settlement">结算明细</div>
                        <div class="e-table">
                            <div
                                class="errorMsg"
                                v-if="errorSettlementMsg.length > 0"
                            >
                                <span>
                                    {{ errorSettlementMsg.join(',') }}
                                </span>
                            </div>
                            <el-table
                                :data="settlementData"
                                border
                                style="width: 100%"
                                ref="settlementTable"
                                :row-class-name="tableRowClassName"
                                :tree-props="{
                                    children: 'children',
                                    hasChildren: 'hasChildren'
                                }"
                                row-key="uuid"
                                :max-height="$store.state.tableHeight"
                                v-sortTable="{ 'tableData': settlementData, '_this': this, 'ref': 'settlementTable' }"
                            >
                                <el-table-column
                                    prop="materialClassName"
                                    label="物资类别"
                                    min-width="170"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="materialName"
                                    label="物资名称"
                                    min-width="130"
                                >
                                </el-table-column>
                                <el-table-column prop="spec" label="规格">
                                </el-table-column>
                                <el-table-column prop="texture" label="材质">
                                </el-table-column>
                                <el-table-column prop="unit" label="计量单位">
                                </el-table-column>
                                <el-table-column
                                    prop="warehouseName"
                                    label="仓库"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="settledQuantity"
                                    label="调价结算数量"
                                    width="100"
                                >
                                </el-table-column>
                                <el-table-column
                                    label="调价验收单价(元)"
                                    width="150"
                                    prop="acceptancePrice"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="settledPrice"
                                    label="调价结算单价(元)"
                                    width="150"
                                >
                                </el-table-column>
                                <el-table-column
                                    label="调价结算不含税金额(元)"
                                    width="170"
                                    prop="settledAmount"
                                >
                                </el-table-column>
                                <el-table-column
                                    label="价差(元)"
                                    width="120"
                                    prop="difference"
                                >
                                </el-table-column>
                                <el-table-column
                                    label="税额差额(元)"
                                    width="120"
                                    prop="taxDifference"
                                >
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>

                    <!-- 服务费用 -->
                    <div id="serviceChargeCon" class="con">
                        <div class="tabs-title" id="serviceCharge">
                            服务费用
                        </div>
                        <div class="e-table">
                            <div
                                class="errorMsg"
                                v-if="errorServiceFeeMsg.length > 0"
                            >
                                <span>
                                    {{ errorServiceFeeMsg.join(',') }}
                                </span>
                            </div>
                            <el-table
                                :data="serviceFeeData"
                                border
                                style="width: 100%"
                                :row-class-name="tableRowClassNameF"
                                ref="serviceFeeTable"
                                :max-height="$store.state.tableHeight"
                                v-sortTable="{ 'tableData': serviceFeeData, '_this': this, 'ref': 'serviceFeeTable' }"
                            >
                                <el-table-column
                                    label="合同编号"
                                    fixed
                                    min-width="150"
                                    prop='contractBillNo'
                                >
                                </el-table-column>
                                <el-table-column
                                    label="结算单位"
                                    min-width="190"
                                    prop='settlementUnitName'
                                >
                                </el-table-column>
                                <el-table-column label="清单名称" width="100" prop='contractDtlName'>
                                </el-table-column>
                                <el-table-column label="数量" width="100" prop='quantity'>
                                </el-table-column>
                                <el-table-column
                                    prop="price"
                                    label="单价(元)"
                                    width="100"
                                >
                                </el-table-column>
                                <el-table-column label="金额(元)" width="100" prop='amount'></el-table-column>
                                <el-table-column label="发票编号" width="130" prop='invoiceNo'>
                                </el-table-column>
                                <el-table-column label="税率%" width="130" prop='taxRate'></el-table-column>
                                <el-table-column label="税额（元）" width="130" prop='taxAmount'></el-table-column>
                                <el-table-column
                                    prop="totalAmount"
                                    label="税价合计（元）"
                                    width="130"
                                ></el-table-column>
                            </el-table>
                        </div>
                    </div>
                    <!-- 附件信息 -->
                    <div id="accessoryCon" class="con">
                        <div class="tabs-title" id="accessory">附件信息</div>
                        <attach-comp
                            :relationId="billid"
                            bucketName="materialsettle"
                            v-if="objFlag.flag5"
                            isView
                        />
                        <div class="seize-a-seat" v-else>
                            <i class="el-icon-loading"></i>
                        </div>
                    </div>
                    <!-- 审核历史 -->
                    <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <AcceptanceHistory
                            :billType="1036"
                            :billId="billid"
                            @historyTableHeight='historyTableHeight'
                        ></AcceptanceHistory>
                    </div>
                </div>
            </el-tabs>
        </div>
        <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
        <div class="buttons">
            <!-- <el-button
                type="primary"
                style="background: #2e61d7"
                v-if="formData.state == 1 || formData.state == 9 || formData.state == 2"
                >打印</el-button
            > -->
            <el-button
                type="primary"
                style="background: #2e61d7"
                v-if="formData.state === 2 && (formData.redBillState === '' || formData.redBillState === -1)"
                @click="redSingle"
                >冲红单</el-button
            >
            <exaButtons
                :auditState="auditState"
                @exas="exas"
                :state="formData.state"
                :founderId="formData.founderId"
                v-if="formData.state !== 5"
                :isPrint="formData.state === 1 || formData.state === 2"
            ></exaButtons>
            <el-button @click="handleClose">关闭</el-button>
        </div>
    </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
import { mapMutations, mapState } from 'vuex'
import { showLoading, hideLoading, openAppClient } from '@/utils/common'
import AttachComp from '@/components/common/attachIndex'
import request from '@/api/materials/materialAcceptance'
import priceSetRequest from '@/api/materialSettlement/priceSettlement'
import { getUuid } from '@/utils/common'
import AcceptanceHistory from '@/pages/materialsmanagement/checkAdmin/AcceptanceHistory'
import exaButtons from '@/components/common/exaButtons'
import { webprintReport, numToChinese } from '@/utils/common'

export default {
    components: {
        AttachComp,
        AcceptanceHistory,
        exaButtons
    },
    data () {
        return {
            tabsName: 'baseInfo',
            settlementData: [], // 结算明细数据
            serviceFeeData: [], //服务费用数据
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            //基本信息表单数据
            formData: {
                acceptancePersonnelId: '',
                acceptancePersonnelName: '',
                amount: '',
                baseCurAmount: 0,
                baseCurFreight: 0,
                baseCurId: '',
                baseCurName: '',
                baseCurRate: '',
                baseCurTaxAmount: 0,
                baseCurTotalAmount: 0,
                billId: '',
                billNo: '',
                businessType: 0,
                currency: '',
                currencyId: '',
                easId: '',
                evaluationLevel: '',
                founderId: '',
                founderName: '',
                freight: '',
                gmtCreate: '',
                gmtModified: '',
                invoiceNo: '',
                isRed: 0,
                nullifyCreated: '',
                nullifyCreator: '',
                nullifyCreatorId: '',
                nullifyDescription: '',
                nullifyReason: '',
                orgId: '',
                orgName: '',
                redBillId: '',
                redBillNo: '',
                redBillState: null,
                remarks: '',
                rmbAmount: 0,
                rmbFreight: 0,
                rmbId: '',
                rmbName: '',
                rmbRate: 0,
                rmbTaxAmount: 0,
                rmbTotalAmount: 0,
                settlementDate: '',
                settlementUnitId: '',
                settlementUnitName: '',
                sourceBillId: '',
                sourceBillNo: '',
                sourceId: '',
                sourceNumber: '',
                state: 0,
                taxAmount: '',
                taxDifference: '',
                taxRate: '',
                totalAmount: '',
                workId: ''
            },
            objFlag: {
                flag5: false
            },
            billid: '',
            orgId: '', //机构id
            orgName: '', //机构名称
            businessTypeList: [
                {
                    value: 0,
                    key: '零星采购计划'
                },
                {
                    value: 1,
                    key: '物资采购合同'
                },
                {
                    value: 2,
                    key: '调入（调拨单）'
                }
            ],
            formDataRules: {
                businessType: [
                    {
                        required: true,
                        message: '请选择业务类型',
                        trigger: 'blur'
                    }
                ],
                settlementUnitName: [
                    {
                        required: true,
                        message: '请选择结算单位',
                        trigger: 'blur'
                    }
                ],
                amount: [
                    {
                        required: true,
                        message: '请输入验收金额',
                        trigger: 'blur'
                    }
                ],
                taxRate: [
                    { required: true, message: '请输入税率', trigger: 'blur' }
                ],
                taxAmount: [
                    { required: true, message: '请输入税额', trigger: 'blur' }
                ],
                totalAmount: [
                    {
                        required: true,
                        message: '请输入税价合计',
                        trigger: 'blur'
                    }
                ],
                freight: [
                    {
                        required: true,
                        message: '请输入服务费用',
                        trigger: 'blur'
                    }
                ],
                currency: [
                    {
                        required: true,
                        message: '请根据选择的结算明细带入币种',
                        trigger: 'blur'
                    }
                ],
                invoiceNo: [
                    {
                        required: true,
                        message: '请填写发票号',
                        trigger: 'blur'
                    }
                ],
                baseCurName: [
                    {
                        required: true,
                        message: '请根据选择的结算明细带入本位币',
                        trigger: 'blur'
                    }
                ],
                baseCurRate: [
                    {
                        required: true,
                        message: '请根据选择的结算明细带入本位币汇率',
                        trigger: 'blur'
                    }
                ]
            },
            auditState: {},
            auditParams: {
                // 审核
                billId: '',
                billType: '1036',
                freeNextUnitIndex: 0,
                freeNextUser: '',
                isPass: true,
                isShareInAudit: true,
                opinion: '',
                orgId: '',
                orgName: '',
                userId: '',
                workId: ''
            },
            nullifyParams: {
                // 作废
                billId: this.$route.query.billid,
                billType: '1036',
                nullifyDescription: '',
                nullifyReason: '',
                nullifyCreated: '',
                nullifyCreator: '',
                nullifyCreatorId: ''
            },
            errorList: [], //控制导航栏感叹号的显示
            errorSettlementMsg: [], // 结算明细
            errorServiceFeeMsg: [], // 服务费用
            redBillStateStyle: {
                width: '300px',
                height: '30px',
                color: '#fff',
                backgroundColor: '',
                'text-align': 'center'
            },
            redFormData: null,
            jsdwData: {
                businessUnitTypes: [],
                keyword: '',
                limit: 10,
                orgId: '',
                outerTypes: [],
                page: 1,
                states: [],
                type: [0, 1, 2],
                supplierTypes: [],
                subcontractorTypes: [],
                businessTypes: []
            },
            jsdwIds: null,
            isSubmit: false,
            settlementList: [], // 验收已选数据
            serviceFeeList: [], // 服务费用已选数据
            settlementDelData: [],
            isServiceFee: false,
            isRedSingle: false,
            isBaseCurRate: true,
            historyData: [],
            businessType: ''
        }
    },
    computed: {
        ...mapState({
            currencyForm: state => state.equip.equipData.currencyForm //币种
        }),
        // //状态
        // statusLable () {
        //     return param => {
        //         const state = this.$store.state.settlementManagement.ysState
        //         const obj = state.find(x => x.value == param)
        //         return obj ? obj.label : ''
        //     }
        // },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 100 - this.lastConHeight
        },
        // 红单状态
        redBillStateFun () {
            let redState = ''
            switch (this.formData.redBillState) {
            case 0:
                redState = '冲销中'
                break
            case 1:
                redState = '冲销中'
                break
            case 2:
                redState = '已冲销'
                break
            case 3:
                redState = '红单'
                break
            }
            return redState
        }
    },
    watch: {
        // 本位币和币种一样的时候，值为1；不一样的时候，填写正数，不能为0，保留4位小数
        'formData.currency' (newData, oldData) {
            if (this.formData.currency == this.formData.baseCurName) {
                this.isBaseCurRate = true
                this.formData.baseCurRate = 1
            } else {
                this.isBaseCurRate = false
                if (oldData != '') {
                    this.formData.baseCurRate = null
                }
            }
        },
        //给错误标签加上提醒
        errorList: newData => {
            const tabs = document.querySelectorAll('.el-tabs__item')
            tabs.forEach(DOM => {
                const { childNodes } = DOM
                if (childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item => {
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        },
        'formData.redBillState' () {
            if (this.formData.redBillState == 3) {
                this.redBillStateStyle.backgroundColor = '#FF2300'
            } else if (
                this.formData.redBillState == 0 ||
                this.formData.redBillState == 1
            ) {
                this.redBillStateStyle.backgroundColor = '#FFA40D'
            } else if (this.formData.redBillState == 2) {
                this.redBillStateStyle.backgroundColor = 'rgb(153,153,153)'
            }
        },
        // 监听结算明细的子级是否有数据, 如果没有数据,则服务费用处不显示新增和删除按钮
        settlementData: {
            handler: function () {
                if (this.settlementData.length < 1) {
                    this.isServiceFee = false
                    this.formData.sourceBillId = ''
                } else {
                    // 如果每一个子项的changeType都为 -1  就说明都删除了, 那服务费用就不能显示 新增/删除按钮
                    let arr = []
                    this.settlementData.forEach(item => {
                        let isData = item.children.every(
                            its => its.changeType === -1
                        )
                        arr.push(isData)
                    })
                    let isSubmit = arr.every(i => i === true)
                    if(isSubmit) {
                        this.isServiceFee = false
                        this.formData.sourceBillId = ''
                    }else {
                        this.isServiceFee = true
                    }
                }
            },
            deep: true
        },
        // 监听结算明细的子级是否有数据, 如果结算明细删除至没有数据,那么服务费用中如果有数据则需要删除服务费用中的数据
        isServiceFee () {
            if (!this.isServiceFee) {
                for (let i = 0; i < this.serviceFeeData.length; i++) {
                    if (this.serviceFeeData[i]['dtlId']) {
                        this.$set(this.serviceFeeData[i], 'changeType', -1)
                        this.$set(this.serviceFeeData[i], 'amount', 0)
                    } else {
                        this.serviceFeeData.splice(i, 1)
                        i--
                    }
                }
                this.formData.freight = this.serviceFeeData
                    .reduce((pre, c) => (pre += +c.amount || 0), 0)
                    .toFixed(2)
            }
        },
    },
    created () {
        let data = JSON.parse(localStorage.getItem('vuex'))
        this.orgId = data.userInfo.orgInfo.orgId
        this.orgName = data.userInfo.orgInfo.orgName
        this.billid = this.$route.query.billid
        this.auditParams.billId = this.$route.query.billid
        this.getAllData()
    },
    mounted () {
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = [
            'baseInfo',
            'settlement',
            'serviceCharge',
            'accessory',
            'auditHistory'
        ]
        this.tabArr = arr
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const $item = document.getElementById(item)
                    let itemTop = null
                    if ($item) {
                        itemTop = $item.offsetTop + 20
                    }
                    return itemTop
                })
            }
            const scrollTop =
                document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if (scrollTop + 50 >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        })

        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        })
        this.scorllDtl()
    },
    methods: {
        ...mapMutations(['setPopConfirm', 'setAuditParams', 'setSelectedInfo']),
        //如果是新增后,直接跳转到编辑页的情况需要跳转到第二个标签
        scorllDtl () {
            if (this.$route.query.name) {
                setTimeout(() => {
                    //因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                    let obj = {
                        name: this.$route.query.name
                    }
                    this.tabsName = this.$route.query.name
                    this.onChangeTab(obj)
                }, 200)
            }
        },
        getAllData () {
            showLoading()
            Promise.all([
                this.getBasicData(), //进入页面就获取基本信息数据
                this.getAttach(), // 附件列表
                this.getUnitInfo() // 获取按钮状态
            ]).finally(() => {
                hideLoading()
            })
        },

        //获取基本信息数据
        async getBasicData () {
            let data = await priceSetRequest.getBasicInfo(this.billid)
            this.redFormData = this._.cloneDeep(data)
            this.businessType = this.businessTypeList.find(
                item => item.value === data.businessType
            ).key
            if (data.redBillState == '3') {
                this.formData = data
                this.isRedSingle = true
            } else {
                this.formData = data
            }

            await this.getSettlementList() // 结算明细表格数据
            await this.getServeList() // 服务费用表格数据
        },

        // 源单编号-跳转到现场收料的详情页
        sourceBillNoClick () {
            let url = ''
            let name = ''
            switch (this.formData.businessType) {
            case 0:
                url = '/sporadicPurchaseParticulars'
                name = '查看零星采购计划'
                break
            case 1:
                url = '/ctMaterialApplyShow'
                name = '查看物资采购合同'
                break
            case 2:
                url = '/revolveAllocationShow'
                name = '查看调入(调拨单)'
                break
            }
            openAppClient(
                `${url}?billid=${this.formData.sourceBillId}&isview=${true}`,
                `${name}`
            )
        },

        // ------------------------------结算明细---------------------------------------

        // 获取结算明细表格数据(弹窗好了过后最终需要调的接口)
        async getSettlementList () {
            let res = await priceSetRequest.getSettlementList(this.billid)
            if (!Array.isArray(res)) return
            res.forEach(item => {
                item.materialClassName = item.topClassName
                item.uuid = getUuid()
                item.children.forEach(i => {
                    i.uuid = i.dtlId
                })
                const count = +(item.children
                    .reduce((prev, c) => (prev += +c.settledAmount || 0), 0))
                    .toFixed(2)
                item.materialName = `金额小计： ${count}`
            })
            this.settlementData = res
        },

        // 如果changeType是删除,则隐藏这一行
        tableRowClassName ({ row }) {
            if (row.changeType === -1) {
                return 'warning-row'
            }
            return ''
        },

        // ---------------------------------服务明细---------------------------------

        // 获取服务费用表格数据(弹窗做好后,需要放开注释的)
        async getServeList () {
            let res = await priceSetRequest.getServeList(this.billid)
            if (Array.isArray(res)) {
                this.serviceFeeData = res
            }
        },

        tableRowClassNameF ({ row }) {
            if (row.changeType === -1) {
                return 'warning-row'
            }
            return ''
        },

        // -------------------在点击下面几个按钮前,需要做前置判断-------------------------
        //设置错误标签
        setError (name) {
            if (!this.errorList.find(x => x === name)) {
                this.errorList.push(name)
            }
        },
        //清除错误标签
        clearError (name) {
            const index = this.errorList.findIndex(x => x === name)
            if (index !== -1) {
                this.errorList.splice(index, 1)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item => {
                let index = this.tabArr.findIndex(x => x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },
        // 设置结算明细有错误时在表格上面显示的错误信息
        setErrorSettlementMsg (msg) {
            let index = this.errorSettlementMsg.findIndex(x => x === msg)
            if (index === -1) {
                this.errorSettlementMsg.push(msg)
            }
        },
        // 设置服务费用有错误时在表格上面显示的错误信息
        setErrorServiceFeeMsg (msg) {
            let index = this.errorServiceFeeMsg.findIndex(x => x === msg)
            if (index === -1) {
                this.errorServiceFeeMsg.push(msg)
            }
        },
        // 点击左边的Tab标签
        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        //保存基本信息时需要检测的
        updateBaseInfo () {
            return new Promise((resolve, reject) => {
                this.$refs.formDataRef.validate(valid => {
                    if (valid) {
                        if (this.formData.redBillState == 3) {
                            this.redFormData.remarks = this.formData.remarks
                        }
                        priceSetRequest
                            .basicInfoSave(
                                this.formData.redBillState == 3
                                    ? this.redFormData
                                    : this.formData
                            )
                            .then(() => {
                                this.clearError('baseInfo')
                                resolve()
                            })
                            .catch(err => {
                                reject(err)
                                this.setError('baseInfo')
                            })
                    } else {
                        this.setError('baseInfo')
                        reject('基本信息错误')
                    }
                })
            })
        },
        // 保存结算明细时需要检测的
        saveSettlement () {
            this.errorSettlementMsg = []
            return new Promise((resolve, reject) => {
                if (this.isSubmit) {
                    // 如果点击的是提交审核才需要判断结算明细是否为空,为空时不能提交审核
                    if (this.settlementData.length < 1) {
                        this.setErrorSettlementMsg('请选择需结算的数据')
                        this.setError('settlement')
                        reject('结算明细错误')
                        return
                    } else {
                        // 如果每一个子项的changeType都为 -1  就说明都删除了, 那就不能提交审核
                        let arr = []
                        this.settlementData.forEach(item => {
                            let isData = item.children.every(
                                its => its.changeType === -1
                            )
                            arr.push(isData)
                        })
                        let isSubmit = arr.every(i => i === true)
                        if (isSubmit) {
                            this.setErrorSettlementMsg('请选择需结算的数据')
                            this.setError('settlement')
                            reject('结算明细错误')
                            return
                        }
                    }
                }
                this.settlementData.forEach(its => {
                    // 只需验证顶级的物资类别是否有
                    !its.materialClassName
                        ? this.setErrorSettlementMsg('请填写物资类别')
                        : ''
                    its.children.forEach(item => {
                        if (item.changeType !== -1) {
                            !item.materialName
                                ? this.setErrorSettlementMsg('请填写物资名称')
                                : ''
                            !item.unit
                                ? this.setErrorSettlementMsg('请填写计量单位')
                                : ''
                            !item.warehouseName
                                ? this.setErrorSettlementMsg('请填写仓库')
                                : ''
                            item.settledQuantity === '' ||
                            item.settledQuantity === null
                                ? this.setErrorSettlementMsg(
                                    '请填写调价结算数量'
                                )
                                : ''
                            item.settledPrice === '' ||
                            item.settledPrice === null || isNaN(item.settledPrice)
                                ? this.setErrorSettlementMsg(
                                    '请计算调价结算单价'
                                )
                                : ''
                            item.settledAmount === '' ||
                            item.settledAmount === null || isNaN(item.settledAmount)
                                ? this.setErrorSettlementMsg(
                                    '请填写调价结算不含税金额'
                                )
                                : ''
                            item.acceptancePrice === '' ||
                            item.acceptancePrice === null
                                ? this.setErrorSettlementMsg(
                                    '请带出调价验收单价'
                                )
                                : ''
                        }
                    })
                })
                if (this.errorSettlementMsg.length > 0) {
                    this.setError('settlement')
                    reject('结算明细错误')
                    return
                } else {
                    this.settlementData.push(...this.settlementDelData)
                    // this.setSelectedInfo(this.settlementData)
                    // openAppClient('/showSelectedData', '选择结果')
                    priceSetRequest
                        .saveSettlement(this.settlementData)
                        .then(() => {
                            this.getSettlementList()
                            this.clearError('settlement')
                            resolve()
                        })
                        .catch(err => {
                            this.errorSettlementMsg[0] = err.message
                            this.setError('settlement')
                            reject(err)
                        })
                }
            })
        },
        // 保存服务明细时需要检测的
        saveServiceFee () {
            this.errorServiceFeeMsg = []
            return new Promise((resolve, reject) => {
                // 如果是基本信息处验结一体勾选中，则服务费用明细中发票编号必填
                if (this.formData.isAccepSettle) {
                    this.serviceFeeData.every(item => {
                        if (!item.invoiceNo) {
                            return this.setErrorServiceFeeMsg('请填写发票编号')
                        }
                    })
                }
                // 检测必填项是否全部填写完毕
                this.serviceFeeData.forEach(item => {
                    if (item.changeType !== -1) {
                        !item.settlementUnitName
                            ? this.setErrorServiceFeeMsg('请填写结算单位')
                            : ''
                        !item.contractDtlName
                            ? this.setErrorServiceFeeMsg('请填写清单名称')
                            : ''
                        !item.quantity
                            ? this.setErrorServiceFeeMsg('请填写数量')
                            : ''
                        item.price === '' || item.price === null || isNaN(item.price)
                            ? this.setErrorServiceFeeMsg('请填写单价(元)')
                            : ''
                        item.amount === '' || item.amount === null || isNaN(item.amount)
                            ? this.setErrorServiceFeeMsg('请填写金额(元)')
                            : ''
                        item.totalAmount === '' || item.totalAmount === null || isNaN(item.totalAmount)
                            ? this.setErrorServiceFeeMsg('请填写税价合计(元)')
                            : ''
                    }
                })
                if (this.errorServiceFeeMsg.length > 0) {
                    this.setError('serviceCharge')
                    reject('服务费用错误')
                    return
                } else {
                    // 如果必填项已全部填完,那么才发送保存服务费用的接口,如果报错依然需要定位到具体位置
                    priceSetRequest
                        .saveServiceFee(this.serviceFeeData)
                        .then(() => {
                            this.getServeList()
                            this.clearError('serviceCharge')
                            resolve()
                        })
                        .catch(err => {
                            this.errorServiceFeeMsg[0] = err.message
                            this.setError('serviceCharge')
                            reject(err)
                        })
                }
            })
        },
        // 保存所有数据
        saveAll () {
            showLoading()
            this.errorList = []
            // 汇总验收数量
            let count = 0
            let countSum = 0
            this.settlementData.forEach(item => {
                count = +(item.children
                    .reduce((pre, c) => (pre += +c.acceptanceQuantity || 0), 0))
                    .toFixed(2)
                countSum += +count
            })
            this.formData.acceptanceQuantity = +countSum.toFixed(2)
            Promise.all([
                this.updateBaseInfo(),
                this.saveSettlement(),
                this.saveServiceFee()
            ])
                .then(() => {
                    hideLoading()
                    this.clientPop('suc', '保存成功')
                })
                .catch(err => {
                    console.log('errMsg：', err)
                    // this.clientPop('err', '保存失败', () => {
                    this.scorllError()
                    // })
                })
                .finally(() => {
                    hideLoading()
                })
        },
        // 提交审核
        submitReview () {
            showLoading()
            this.errorList = []
            Promise.all([
                this.updateBaseInfo(),
                this.saveSettlement(),
                this.saveServiceFee()
            ])
                .then(() => {
                    request.commitAudit(this.auditParams)
                    this.clientPop('suc', '提交成功', this.handleClose)
                })
                .catch(err => {
                    console.log('errMsg：', err)
                    // this.clientPop('err', '提交失败', () => {
                    this.scorllError()
                    // })
                })
                .finally(() => {
                    hideLoading()
                })
        },

        // 审核
        onAudit () {
            showLoading()
            this.setAuditParams(this.auditParams)
            // 客户端弹窗弹出本地页面
            openAppClient('/exaDialog', '填写审核意见', () => {
                const auditParams = JSON.parse(localStorage.vuex).auditParams
                showLoading()
                request
                    .audit(auditParams)
                    .then(() => {
                        this.clientPop('suc', '审核成功', this.handleClose)
                    })
                    .finally(() => {
                        hideLoading()
                    })
            }, null, null, null, 'small')
        },

        // 撤销审核
        undoAudit () {
            this.clientPop('info', '确定返回上一步操作吗?', () => {
                showLoading()
                request
                    .undoAudit(this.auditParams)
                    .then(() => {
                        this.clientPop('suc', '撤回成功', this.handleClose)
                    })
                    .finally(() => {
                        hideLoading()
                    })
            })
        },
        // 作废
        nullify () {
            this.setAuditParams(this.nullifyParams)
            // 客户端弹窗弹出本地页面
            openAppClient('/nullifyDialog', '单据作废原因', () => {
                const auditParams = JSON.parse(localStorage.vuex).auditParams
                showLoading()
                request
                    .nullify(auditParams)
                    .then(() => {
                        this.clientPop('suc', '作废成功', this.handleClose)
                    })
                    .finally(() => {
                        hideLoading()
                    })
            }, null, null, null, 'small')
        },
        // 删除
        deleteData () {
            this.clientPop('info', this.oneDeleteErr, () => {
                showLoading()
                priceSetRequest
                    .basicInfoDelete(this.billid)
                    .then(() => {
                        this.clientPop('suc', '删除成功', this.handleClose)
                    })
                    .finally(() => {
                        hideLoading()
                    })
            })
        },
        // 打印
        async print () {
            const printData = async ()=>{
                showLoading()
                try{
                    const  params =  {
                        'reportTitle': '物资调价结算单', //报表名
                        'orgName': this.formData.orgName, //单据机构
                        'reportQRUri': '', //报表内容URI
                        'billNo': this.formData.billNo, //单据编码
                        'summaryInfoItems': [ //基本信息
                            { 'label': '供货单位', 'value': this.formData.settlementUnitName, 'isFullRow': false }, //isFullRow:是否占整行
                            { 'label': '附件', 'value': '    ' + '张', 'isFullRow': false },
                            { 'label': '发票编号', 'value': this.formData.invoiceNo, 'isFullRow': false },
                            { 'label': '结算依据', 'value': this.formData.sourceBillNo, 'isFullRow': false },
                            { 'label': '结算日期', 'value': this.formData.settlementDate, 'isFullRow': false },
                            { 'label': '不含税金额(元)', 'value': this.formData.amount, 'isFullRow': false },
                            { 'label': '税率(%)', 'value': this.formData.taxRate + '%', 'isFullRow': false },
                            { 'label': '可抵扣税额(元)', 'value': this.formData.taxAmount, 'isFullRow': false },
                            { 'label': '税价合计金额(元)', 'value': this.formData.totalAmount, 'isFullRow': false },
                            { 'label': '税额差额(元)', 'value': this.formData.taxDifference, 'isFullRow': false },
                            { 'label': '税价合计金额大写', 'value': numToChinese(this.formData.totalAmount), 'isFullRow': false },
                            { 'label': '备注信息', 'value': this.formData.remarks, 'isFullRow': true },
                        ],
                        'tables': [] //表格
                    }
                    // 验收明细
                    let newArr = this._.cloneDeep(this.settlementData)
                    newArr.forEach(item=>{item.children.forEach(it=> newArr.push(it))})
                    const acceptanceList = {
                        'tableTitle': '验收明细',
                        'tableContent': {
                            '物资类别': 'materialClassName',
                            '物资名称': 'materialName',
                            '规格': 'spec',
                            '材质': 'texture',
                            '单位': 'unit',
                            '调价验收数量': 'acceptanceQuantity',
                            '调价验收单价': 'acceptancePrice',
                            '调价验收金额': '',
                            '调价结算单价': 'settledPrice',
                            '调价结算金额': 'settledAmount',
                            '税额差额(元)': 'taxDifference',
                        },
                        'tableData': newArr, //表格数据
                    }
                    params.tables.push(acceptanceList)
                    //审核历史
                    const historyTable  = await request.getAuditHistory(this.auditParams)
                    const historyList = {
                        'tableTitle': '审核历史',
                        'tableContent': {
                            '审核级次': 'unitName',
                            '审核人': 'assignUser',
                            '审核人岗位': 'userTitle',
                            '通知时间': 'notifyTime',
                            '审核时间': 'completeTime',
                            '审核意见': 'opinion',
                        },
                        'tableData': historyTable, //表格数据
                    }
                    params.tables.push(historyList)
                    hideLoading()
                    return params
                }catch(err) {
                    console.log(err)
                    this.clientPop('err', '打印失败')
                    hideLoading()
                }
            }
            const data = await printData()
            webprintReport(data)
        },
        // 点击冲红单
        redSingle () {
            this.$router.replace({
                path: '/priceSettlementAdd',
                query: { isRedSingle: '1', billid: this.billid }
            })
        },

        // ---------------------------下面按钮---------------------------
        // 获取按钮状态
        async getUnitInfo () {
            this.auditState = await request.getCurrentUnitInfo(
                this.auditParams
            )
        },

        // 点击下面几个不同的按钮做不同的操作
        exas (arg) {
            if (arg === 'submit') {
                this.isSubmit = false
                this.saveAll() // 保存所有数据
            } else if (arg === 'submitCommit') {
                this.isSubmit = true
                this.submitReview() // 保存并提交
            } else if (arg === 'audit') {
                this.onAudit() // 审核
            } else if (arg === 'undoAudit') {
                this.undoAudit() // 撤销审核
            } else if (arg === 'nullify') {
                this.nullify() // 作废
            } else if (arg === 'deleteData') {
                this.deleteData() // 删除
            } else if(arg === 'print') {
                this.print() // 打印
            }
        },

        // ------------------------上面小刘---------

        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('auditHistoryCon') && this.historyData.length > 0) {
                    const lastConHeight =
                        document.getElementById('auditHistoryCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    console.log('this.lastConHeight', this.lastConHeight)
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        historyTableHeight (data) {
            this.historyData = data
        },

        //查询附件信息
        getAttach () {
            this.objFlag.flag5 = true
        },
        //关闭
        handleClose () {
            hideLoading()
            this.$router.replace('/priceSettlementList')
        },
        showState (state) {
            const _state = this.$store.state.settlementManagement.ysState
            const obj = _state.find(x => x.value === Number(state))
            return obj.label
        }
    }
}
</script>

<style lang="scss" scoped>
.buttons {
    left: 0;
}
.e-form {
    margin-bottom: 80px;
    padding: 0 20px;
    .tabs-title::before {
        content: '';
        height: 22px;
        width: 8px;
        border-radius: 40px;
        background-color: #2e61d7;
        display: block;
        position: absolute;
        left: 20px;
        margin-right: 20px;
    }
}

.e-table {
    background: #fff;
}
::v-deep.el-table .warning-row {
    display: none;
}
// ::v-deep.el-table__body-wrapper::-webkit-scrollbar{
//      width: 6px !important; // 横向滚动条
//     height: 10px !important// 纵向滚动条
// }

::v-deep .el-table__body-wrapper::-webkit-scrollbar {
    width: 6px; // 横向滚动条
    height: 10px; // 纵向滚动条
}
// 滚动条的滑块
::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb {
    background-color: #ddd;
    border-radius: 5px;
}

.el-tab-pane {
    margin-left: -10px;
}
::v-deep .el-table__fixed{
        height: 100% !important
}
</style>
